package com.fatri.lessionsimple

import android.opengl.GLSurfaceView
import android.os.Bundle
import android.view.MotionEvent
import androidx.appcompat.app.AppCompatActivity
import com.fatri.lessionsimple.opengl.IDrawer
import com.fatri.lessionsimple.opengl.drawer.*
import kotlinx.android.synthetic.main.act_simple_render.*
import kotlin.math.absoluteValue

class SimpleRenderActivity : AppCompatActivity() {

    lateinit var drawer: IDrawer

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.act_simple_render)

//        drawer = TriangleDrawer(this)

//        val bitmap = BitmapFactory.decodeResource(resources, R.drawable.tushe)
//        drawer = BitmapDrawer(bitmap)
        initRender()


        btn_render.setOnClickListener { gl_surface.requestRender() }
    }

    private lateinit var render: TransferRander
    private fun initRender() {
        gl_surface.setEGLContextClientVersion(2)
//        gl_surface.setRenderer(SimpleRender(PicDrawer::class.java,this))  //静态渲染器

        gl_surface.setRenderer(
            TransferRander(
                this
            ).also { render = it }) //变换渲染器

        gl_surface.renderMode = GLSurfaceView.RENDERMODE_WHEN_DIRTY  //手动刷新，当调用requestRender时刷新

    }

    override fun onDestroy() {
//        drawer.release()
        super.onDestroy()
    }


    var curX = 0f
    var curY = 0f

    var downX = 0f
    var downY = 0f
    override fun onTouchEvent(event: MotionEvent): Boolean {
        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                downX = event.x
                downY = event.y
                curX = event.x
                curY = event.y
            }
            MotionEvent.ACTION_MOVE -> {

                //平移示例，测试可用
//                val dx = event.x - curX
//                val dy = event.y - curY
//                curX = event.x
//                curY = event.y
//                render.translate(dx/100f, -dy/100f)
//                gl_surface.requestRender()


                //旋转示例，测试可用
                val dx = event.x - curX
                val dy = event.y - curY
                curX = event.x
                curY = event.y
                val right = dx> 0
                val top = dy< 0
                var ang = (event.x - downX) % 360
                println("ang:$ang")
                if (dx.absoluteValue>dy.absoluteValue){
                    render.rotate(dx / 5f, 0f, 1f, 0f)
                }else{
                    render.rotate(dy / 5f, 1f, 0f, 0f)
                }
                gl_surface.requestRender()

            }
        }


        return super.onTouchEvent(event)
    }
}